import Cookies from "js-cookie";
import { validateNull } from "./validate";
import { number } from "echarts";

const TokenKey = "Admin-Token";

const ExpiresInKey = "Admin-Expires-In";

export function getToken() {
  return Cookies.get(TokenKey);
}

export function setToken(token) {
  return Cookies.set(TokenKey, token);
}

export function removeToken() {
  return Cookies.remove(TokenKey);
}

export function getExpiresIn() {
  return Cookies.get(ExpiresInKey) || -1;
}

const keyName = "his-";

export function setExpiresIn(time) {
  return Cookies.set(ExpiresInKey, time);
}

export function removeExpiresIn() {
  return Cookies.remove(ExpiresInKey);
}

/**
 * 存储localStorage
 */
export const setStore = (params: any = {}) => {
  let name = params.name;
  const content = params.content;
  const type = params.type;
  name = keyName + name;
  const obj = {
    dataType: typeof content,
    content: content,
    type: type,
    datetime: new Date().getTime(),
  };
  if (type) {
    window.sessionStorage.setItem(name, JSON.stringify(obj));
  } else {
    window.localStorage.setItem(name, JSON.stringify(obj));
  }
};

/**
 * 获取localStorage
 */

export const getStore = (params: any = {}) => {
  let name = params.name;
  const debug = params.debug;
  name = keyName + name;
  let objStr = "";
  let obj: any = {};
  let content: number | String;
  //@ts-ignore
  objStr = window.sessionStorage.getItem(name);
  //@ts-ignore
  if (validateNull(objStr)) objStr = window.localStorage.getItem(name);
  if (validateNull(objStr)) return;
  try {
    obj = JSON.parse(objStr);
  } catch {
    return obj;
  }
  if (debug) {
    return obj;
  }
  if (obj.dataType === "string") {
    content = obj.content;
  } else if (obj.dataType === "number") {
    content = Number(obj.content);
  } else if (obj.dataType === "boolean") {
    // eslint-disable-next-line no-eval
    content = eval(obj.content);
  } else if (obj.dataType === "object") {
    content = obj.content;
  }
  //@ts-ignore
  return content;
};
